<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      :inline="true"
      v-show="showSearch"
      label-width="100px"
      size="medium"
      class="ry_form"
    >
      <el-form-item v-if="YT_roles" :label="$t('common.customer')" prop="customerId">
        <WmsCustomerSelect v-model="queryParams.customerId" size="small"></WmsCustomerSelect>
      </el-form-item>
      <el-form-item label="入库时间" prop="inTime">
        <el-date-picker
          clearable
          size="small"
          v-model="queryParams.inTime"
          type="datetime"
          value-format="yyyy-MM-ddTHH:mm:ss"
          placeholder="选择入库时间"
        >
        </el-date-picker>
      </el-form-item>
      <el-form-item label="所属仓库" prop="warehouseId">
        <WmsAreaCascader
          v-model="queryParams.warehouseId"
          size="small"
        ></WmsAreaCascader>
      </el-form-item>
      <el-form-item class="flex_one tr">
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          >{{ $t('common.search') }}</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
          >{{ $t('common.reset') }}</el-button
        >
      </el-form-item>
    </el-form>
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          >{{ $t('common.add') }}</el-button
        >
      </el-col>
      <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getList"
        :columns="columns"
      ></right-toolbar>
    </el-row>
    <WmsTable
      v-loading="loading"
      :data="wmwarehouseRent"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column
        label="入库时间"
        align="center"
        prop="inTime"
        v-if="columns[0].visible"
      />
      <el-table-column
        label="出库时间"
        align="center"
        prop="outTime"
        v-if="columns[1].visible"
      />
      <el-table-column
        label="开始计费时间"
        align="center"
        prop="startTime"
        v-if="columns[2].visible"
      />
      <el-table-column
        :label="$t('outBound.Expected delivery time')"
        align="center"
        prop="endTime"
        v-if="columns[3].visible"
      />
      <el-table-column
        label="客户名称"
        align="center"
        prop="customerName"
        v-if="columns[4].visible"
      />
      <el-table-column
        label="仓库/库位"
        align="center"
        prop="warehouseName"
        v-if="columns[5].visible"
      >
        <template slot-scope="scope">
          {{ scope.row.warehouseName }}<span v-if="scope.row.areaName"> / </span>{{ scope.row.areaName }}
        </template>
      </el-table-column>
      <el-table-column
        label="日单价"
        align="center"
        prop="rent"
        v-if="columns[6].visible"
      />
      <el-table-column :label="$t('common.operation')" prop="operation" width="100px">
        <template slot-scope="scope">
          <el-button v-if="scope.row.status !== 'CANCEL'" type="text" @click="handleUpdate(scope.row)">{{ $t('common.edit') }}</el-button>
          <el-button type="text" @click="handleDelete(scope.row)">{{ $t('common.del') }}</el-button>
          <el-button v-if="scope.row.status !== 'CANCEL'" type="text" @click="handleClose(scope.row)">关闭</el-button>
        </template>
      </el-table-column>
    </WmsTable>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="50%" append-to-body>
      <el-form
        ref="form"
        :model="form"
        :rules="rules"
        label-width="108px"
        inline
        class="dialog-form-two"
      >
        <el-row :gutter="20">
          <el-col
            v-for="(item, index) in addOrEditColumn"
            :key="index"
            :xs="24"
            :sm="item.col"
            :md="item.col"
            :lg="item.col"
            :xl="item.col"
          >
            <FormComponents :item-obj="item" :form="form" :isedit="true">
              <template slot="warehouseId">
                <WmsAreaCascader v-model="form.warehouseId" size="small"></WmsAreaCascader>
              </template>
              <template slot="customerId">
                <WmsCustomerSelect v-model="form.customerId"></WmsCustomerSelect>
              </template>
            </FormComponents>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">{{ $t('common.confirm') }}</el-button>
        <el-button @click="cancel">{{ $t('common.cancel') }}</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  warehouseRent,
  addWarehouseRent,
  updateWarehouseRent,
  delWarehouseRent,
  exportWarehouseRent,
} from "@/api/wms/stockAge";
import dayjs from "dayjs";
import FormComponents from "@/components/FormComponents/index.vue";
import WmsAreaCascader from "@/components/WmsAreaCascader";
import { listWmsCustomer } from "@/api/wms/customer";

export default {
  name: "WmsReceiptOrderDetail",
  components: { WmsAreaCascader, FormComponents },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 导出遮罩层
      exportLoading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 列表
      wmwarehouseRent: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        inTime: null,
        areaId: null,
        customerId: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        rent: [
          { required: true, message: this.$t('common.pleaseInput'), trigger: "blur" }
        ],
        inTime: [
          { required: true, message: this.$t('common.placeholderSelect'), trigger: "change" }
        ],
        outTime: [
          { required: true, message: this.$t('common.placeholderSelect'), trigger: "change" }
        ],
        startTime: [
          { required: true, message: this.$t('common.placeholderSelect'), trigger: "change" }
        ],
        endTime: [
          { required: true, message: this.$t('common.placeholderSelect'), trigger: "change" }
        ],
        customerId: [
          { required: true, message: this.$t('common.placeholderSelect'), trigger: "change" }
        ]
      },
      columns: [
        { key: 1, label: "入库时间", visible: true },
        { key: 2, label: "出库时间", visible: true },
        { key: 3, label: "开始计费时间", visible: true },
        { key: 4, label: "预计出库时间", visible: true },
        { key: 5, label: this.$t('customer.name'), visible: true },
        { key: 6, label: "仓库/库位", visible: true },
        { key: 7, label: "日单价", visible: true }
      ],
    };
  },
  created() {
    this.getList();
  },
  computed: {
    addOrEditColumn() {
      const base = [
        {
          prop: "inTime",
          label: "入库时间",
          type: "datetime",
          col: 24,
        },
        { prop: "outTime", label: "出库时间", type: "datetime", col: 24 },
        { prop: "startTime", label: "开始计费时间", type: "datetime", col: 24 },
        {
          prop: "endTime",
          label: "预计出库时间",
          type: "datetime",
          col: 24,
        },
        { prop: "rent", label: "日单价", type: "input", col: 24 },
        { slot: "warehouseId", label: '仓库/库位', col: 24 },
      ];
      const customerRoles = [{ slot: "customerId", prop: 'customerId', label: this.$t('common.customer'), col: 24 }]
      if (this.YT_roles) {
        return [ ...base, ...customerRoles,]
      } else {
        return [...base]
      }
    },
    YT_roles() {
      // 暂时判断roles为common不是客户的未YT
      if(this.$store.state.user.roles[0] !== 'common') {
        return true
      }
    },
  },
  methods: {
    // 查询客户
    getCusList() {
      const query = { pageNum: undefined, pageSize: undefined };
      const pageReq = { page: 0, size: 100000 };
      listWmsCustomer(query, pageReq).then((response) => {
        const { content } = response;
        this.wmsCustomerList = content;
      });
    },
    /** 查询列表 */
    getList() {
      this.loading = true;
      const { pageNum, pageSize } = this.queryParams;
      const query = {
        ...this.queryParams,
        pageNum: undefined,
        pageSize: undefined,
      };
      const pageReq = { page: pageNum - 1, size: pageSize };
      warehouseRent(query, pageReq).then((response) => {
        const { content, totalElements } = response;
        this.wmwarehouseRent = content;
        this.total = totalElements;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        inTime: null,
        warehouseId: null,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.queryParams.warehouseId = this.queryParams.warehouseId ? this.queryParams.warehouseId[0] : '';
      this.queryParams.areaId = this.queryParams.areaId && this.queryParams.areaId[1] ? this.queryParams.areaId[1] : '';
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.form = row
      this.open = true
      this.title = this.$t('common.edit');
      this.form.warehouseId = this.form.areaId ? [this.form.warehouseId, this.form.areaId] : this.form.warehouseId
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          // this.form.inTime = dayjs(this.form.inTime).format(
          //   "YYYY-MM-DD HH:mm:ss"
          // );
          // this.form.outTime = dayjs(this.form.outTime).format(
          //   "YYYY-MM-DD HH:mm:ss"
          // );
          // this.form.startTime = dayjs(this.form.outTime).format(
          //   "YYYY-MM-DD HH:mm:ss"
          // );
          // this.form.endTime = dayjs(this.form.outTime).format(
          //   "YYYY-MM-DD HH:mm:ss"
          // );
          this.form = {
            ...this.form,
            warehouseId: this.form.warehouseId ? this.form.warehouseId[0] : '',
            areaId: this.form.warehouseId && this.form.warehouseId[1] ? this.form.warehouseId[1] : '',
          }
          if (this.form.id != null) {
            updateWarehouseRent(this.form).then((response) => {
              this.$modal.msgSuccess("操作成功");
              this.open = false;
              this.resetQuery()
              this.getList();
            });
          } else {
            addWarehouseRent(this.form).then((response) => {
              this.$modal.msgSuccess(this.$t('common.succcessInfo'));
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal
        .confirm(this.$t('common.delMsg'))
        .then(function () {
          return delWarehouseRent(ids);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess(this.$t('common.succcessInfo'));
        })
        .catch(() => {});
    },
    handleClose(row) {
      const ids = row.id || this.ids;
      this.$modal
        .confirm('是否确认关闭编号为"' + ids + '"的数据项？')
        .then(function () {
          const params = {
            id: ids, status: 'CANCEL'
          }
          updateWarehouseRent({...params}).then((response) => {
            this.$modal.msgSuccess("操作成功");
            this.open = false;
            this.getList();
          });
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess(this.$t('common.succcessInfo'));
        })
        .catch(() => {});
    }
  },
};
</script>
